//
//  HLHomeCellPicturesView.swift
//  weibo-snh
//
//  Created by 黄力 on 15/12/20.
//  Copyright © 2015年 HLTest. All rights reserved.
//

import UIKit
import SnapKit

private let picturesViewCellID = "picturesViewCellID"

private let layoutMinMargin: CGFloat = 5

class HLHomeCellPicturesView: UICollectionView {
    
    var picturesUrlArr: [NSURL]? {
        didSet {
            //根据图片张数来设置视图大小
            let viewSize = calculatePicturesViewSize()
            //设置约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(viewSize)
            }
            
            numLabel.text = "\(picturesUrlArr?.count ?? 0)"
            //刷新界面
            reloadData()
        }
    }
    
    //计算当前视图大小
    private func calculatePicturesViewSize() -> CGSize {
        //当是空获取图片数量为0时
        guard let urlArr = picturesUrlArr where urlArr.count > 0 else {
            return CGSizeZero
        }
        //获取约束
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        //图片数量为1
        if urlArr.count == 1 {
            //修改约束
            layout.itemSize = CGSizeMake(150, 120)
            return CGSizeMake(150, 120)
        }
        //pictureView的最大宽度
        let pictureViewMaxWidth = MainScreenWidth - 2 * homeCellTopViewMargin
        //单张图片最小宽度
        let cellMinWidth = (pictureViewMaxWidth - layoutMinMargin * 2) / 3
        //修改约束
        layout.itemSize = CGSizeMake(cellMinWidth, cellMinWidth)
        //图片数量为4
        if urlArr.count == 4 {
            return CGSizeMake(cellMinWidth * 2 + layoutMinMargin, cellMinWidth * 2 + layoutMinMargin)
        }
        //其他情况下计算行数
        let num = CGFloat((urlArr.count - 1) / 3 + 1)
        //计算高度
        let picHeight = cellMinWidth * num + layoutMinMargin * (num - 1)
        
        return CGSizeMake(pictureViewMaxWidth, picHeight)
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //创建布局对象
        let flowLayout = UICollectionViewFlowLayout()
        //设置cell的最小间距
        flowLayout.minimumInteritemSpacing = layoutMinMargin
        flowLayout.minimumLineSpacing = layoutMinMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        //设置背景颜色
        backgroundColor = UIColor.whiteColor()
        //设置数据源
        dataSource = self
        //注册cell
        registerClass(HLPicturesViewCell.self, forCellWithReuseIdentifier: picturesViewCellID)
        //设置界面
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置界面
    private func setupUI() {
        //添加
        addSubview(numLabel)
        
        numLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.centerY.equalTo(self)
        }
    }
    
    private lazy var numLabel: UILabel = UILabel(title: "0", titleColor: UIColor.blueColor(), titleFont: 25)
}

extension HLHomeCellPicturesView: UICollectionViewDataSource {
    
    //设置个数
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picturesUrlArr?.count ?? 0
    }
    
    //设置每个cell的内容
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = dequeueReusableCellWithReuseIdentifier(picturesViewCellID, forIndexPath: indexPath) as! HLPicturesViewCell
        //设置数据
        cell.imageUrl = picturesUrlArr![indexPath.item]
        return cell
    }
}

// MARK: 自定义cell
class HLPicturesViewCell: UICollectionViewCell {
    
    var imageUrl: NSURL? {
        didSet {
            backImageView.sd_setImageWithURL(imageUrl!)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //设置界面
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置界面
    private func setupUI() {
        //添加子控件
        contentView.addSubview(backImageView)
        //设置自动布局
        backImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }
    
    //懒加载图片
    private lazy var backImageView: UIImageView = {
        let imageView = UIImageView()
        //设置填充模式
        imageView.contentMode = .ScaleAspectFill
        //设置超出部分裁剪
        imageView.clipsToBounds = true
        return imageView
    }()
}

